<!-- 单元页面-->
<template>
  <div>
    <!-- 搜索框 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">

      <el-form-item label="楼栋名称" prop="address">
        <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" size="mini" style="width: 9vw ">
          <el-option v-for="item in buildingName" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="单元名称：">
        <el-input v-model="searchForm.unitCode" placeholder="请输入单元名称" size="mini" style="width: 9vw"></el-input>
      </el-form-item>

      <el-form-item label="层数：">
        <el-input v-model="searchForm.floor" placeholder="请输入楼层" size="mini" style="width: 9vw"></el-input>
      </el-form-item>

      <el-form-item label="单元物品：">
        <el-input v-model="searchForm.publicProperty" placeholder="请输入单元物品" size="mini"
                  style="width: 10vw"></el-input>
      </el-form-item>

      <el-form-item>
        <!-- 搜索按钮 -->
        <el-button size="mini" type="primary" @click="fetchData">搜索</el-button>
        <!-- 清除按钮 -->
        <el-button size="mini" type="info" @click="handleReset">清除</el-button>
        <!--添加单元按钮-->
        <el-button size="mini" type="success" @click="showAddUnitModal">添加单元</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
        :visible.sync="isAddUnitModalVisible"
        title="添加单元信息"
        width="50%">
      <AddUnit @submit="handleAddUnit" @unitsAdded="hideDialog"></AddUnit>
    </el-dialog>

    <el-dialog
        :visible.sync="isUpdateUnitModalVisible"
        title="修改单元信息"
        width="50%">
      <UpdateUnit :message="message" @submit="handleUpDateUnit" @unitsUpdate="hideDialog"></UpdateUnit>
    </el-dialog>


    <!--    展示单元列表-->
    <el-table :data="unitList" border stripe>
      <el-table-column v-if="false" align="center" label="单元ID" prop="unitId"></el-table-column>
      <el-table-column align="center" label="楼栋名称" prop="buildingName"></el-table-column>
      <el-table-column align="center" label="单元名称" prop="unitCode"></el-table-column>
      <el-table-column align="center" label="楼层" prop="floor"></el-table-column>
      <el-table-column align="center" label="单元物品" prop="publicProperty"></el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <!--          <el-link style="margin-left: 10px;" type="success" @click="handleEdit(scope.row)"> 查看 </el-link>-->
          <el-link style="margin-left: 10px;" type="primary" @click="showUpdateUnitModal(scope.row.unitId)"> 编辑
          </el-link>
          <el-link style="margin-left: 10px;" type="danger" @click="confirmDelete(scope.row.unitId)"> 删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加分页器 -->
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import AddUnit from '@/components/unit/AddUnit.vue';
import UpdateUnit from '@/components/unit/UpdateUnit.vue';

export default {

  data() {
    return {
      message: '',
      isUpdateUnitModalVisible: false,
      isAddUnitModalVisible: false,
      // 条件查询的数据
      searchForm: {
        unitCode: '',//单元名称
        floor: '',//楼层
        publicProperty: "",//单元物品
        buildingId: ''//楼栋ID
      },
      unitList: [],
      dormitoryTypeMap: {
        0: '女生宿舍',
        1: '男生宿舍',
        2: '混合宿舍'
      },
      buildingName: [],//楼栋集合
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  components: {
    AddUnit,
    UpdateUnit,
  },
  created() {
    this.fetchData();

    this.queryBuildingInformation();
  },
  methods: {
    // 查询楼栋信息
    queryBuildingInformation() {
      // 调用后端接口获取数据
      this.$axios.post('/api/buildings/list', {}, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          // 使用 reduce 构建以 userId 为键，name 为值的对象
          this.buildingName = response.data.data.reduce((arr, user) => {
            // 将当前用户的 userId 作为键，name 作为值，添加到累积的数组中
            arr.push({value: user.buildingId, label: user.buildingName});
            return arr;
          }, []);
        } else {
          this.$message.error(response.data.msg || '查询楼栋信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '查询楼栋信息失败');
      });
    },
    // 成功提示信息
    succeed(msg) {
      this.$message({
        message: msg,
        type: 'success'
      });
    },
    // 提示是否删除
    confirmDelete(unitId) {
      // 弹出确认提示框
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定按钮后执行删除操作
        this.deleteUnit(unitId);
      }).catch(() => {
        // 用户点击取消按钮，不执行任何操作
      });
    },
    hideDialog() {
      this.isAddUnitModalVisible = false;
      this.isUpdateUnitModalVisible = false;
      // 调用搜索方法，重新加载数据
      this.fetchData();
    },
    showAddUnitModal() {
      this.isAddUnitModalVisible = true;
    },
    handleAddUnit() {
      // 处理添加单元信息成功后的逻辑
      // 关闭模态框等操作
      this.isAddUnitModalVisible = false;
    },
    showUpdateUnitModal(unitId) {
      this.message = unitId;
      this.isUpdateUnitModalVisible = true;
    },
    handleUpDateUnit() {
      // 处理添加楼栋信息成功后的逻辑
      // 关闭模态框等操作
      this.isUpdateUnitModalVisible = false;
    },


    // 清除搜索条件
    handleReset() {
      // 清空搜索条件对象
      this.searchForm.buildingId = '';
      this.searchForm.unitCode = '';
      this.searchForm.floor = '';
      this.searchForm.publicProperty = '';
      // 调用搜索方法，重新加载数据
      this.fetchData();
    },

    // 查询单元信息
    fetchData() {
      // 调用后端接口获取数据
      this.$axios.post('/api/units/page?pageNum=' + this.currentPage + '&pageSize=' + this.pageSize, {
        buildingId: this.searchForm.buildingId,
        unitCode: this.searchForm.unitCode,
        floor: this.searchForm.floor,
        publicProperty: this.searchForm.publicProperty,
      }, {headers: {'token': this.$store.getters.getToken}}).then(response => {
        // 请求成功后更新表格数据和分页信息
        if (response.data.code === 200) {
          this.unitList = response.data.data.list;
          this.total = response.data.data.total;
          // 请求成功，处理响应
          this.succeed("查询成功");
        } else {
          this.$message.error(response.data.msg || '获取单元信息失败');
        }
      }).catch(error => {
        this.$message.error(error || '获取单元信息失败');
      });
    },
    handleSizeChange(size) {
      // 每页条数变更
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(page) {
      // 当前页码变更
      this.currentPage = page;
      this.fetchData();
    },
    deleteUnit(unitId) {
      // 发送DELETE请求
      this.$axios.delete(`/api/units/delete/${unitId}`)
          .then(response => {
            if (response.data.code === 200) {
              // 请求成功，处理响应
              this.succeed("删除成功");
              // 在这里可以根据需要执行一些操作，比如更新界面等
              this.fetchData();
            } else {
              this.$message.error(response.data.msg || '删除信息失败');
            }
          })
          .catch(error => {
            // 请求失败，处理错误
            this.$message.error(error || '删除信息失败');
          });
    },
  }
};
</script>


